package com.mes.biz.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Random;

import com.github.pagehelper.PageHelper;
import com.mes.biz.domain.*;
import com.mes.biz.domain.vo.BizOrderMaterialVo;
import com.mes.biz.domain.vo.ConvertRatioNumberUnit;
import com.mes.biz.service.*;
import com.mes.common.constant.BizConstants;
import com.mes.common.core.domain.model.LoginUser;
import com.mes.common.core.page.PageDomain;
import com.mes.common.exception.BizException;
import com.mes.common.utils.DateUtils;
import com.mes.common.utils.SecurityUtils;
import com.mes.common.utils.StringUtils;
import com.mes.common.utils.sql.SqlUtil;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.pagehelper.PageInfo;
import com.mes.common.core.domain.BaseEntity;
import com.mes.common.core.service.BaseServiceImpl;
import com.mes.biz.mapper.BizOrderMaterialMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 销售单物料Service业务层处理
 * @author wy
 * @email wy
 * @date 2023-06-20
 */
@Service
@Transactional(readOnly = true)
public class BizOrderMaterialServiceImpl extends BaseServiceImpl<BizOrderMaterialMapper, BizOrderMaterial> implements BizOrderMaterialService {

    private static final Logger log = LoggerFactory.getLogger(BizOrderMaterialServiceImpl.class);

    @Resource
    private BizOrderService bizOrderService;
    @Resource
    private BizProductInventoryService bizProductInventoryService;
    @Resource
    private BizProductService bizProductService;
    @Resource
    private BizProductInventoryBookService bizProductInventoryBookService;
    @Resource
    private BizOrderProductService bizOrderProductService;
    @Resource
    private BizProductionOrderService bizProductionOrderService;
    @Resource
    private BizOrderMaterialMapper bizOrderMaterialMapper;
    /**
     * 获取单条数据
     * @param bizOrderMaterial 销售单物料
     * @return 销售单物料
     */
    @Override
    public BizOrderMaterial get(BizOrderMaterial bizOrderMaterial) {
        BizOrderMaterial dto = super.get(bizOrderMaterial);
        return dto;
    }

    /**
     * 获取单条数据
     * @param id 销售单物料id
     * @return 销售单物料
     */
    @Override
    public BizOrderMaterial get(String id) {
        BizOrderMaterial dto = super.get(id);
        return dto;
    }

    /**
     * 查询销售单物料列表
     * @param bizOrderMaterial 销售单物料
     * @return 销售单物料
     */
    @Override
    public List<BizOrderMaterial> findList(BizOrderMaterial bizOrderMaterial) {
		List<BizOrderMaterial> bizOrderMaterialList = super.findList(bizOrderMaterial);
        return bizOrderMaterialList;
    }

    /**
     * 分页查询销售单物料列表
     * @param bizOrderMaterial 销售单物料
     * @return 销售单物料
     */
    @Override
    public PageInfo<BizOrderMaterial> findPage(BizOrderMaterial bizOrderMaterial) {
		PageInfo<BizOrderMaterial> page = super.findPage(bizOrderMaterial);
        return page;
    }

    /**
     * 保存销售单物料
     * @param bizOrderMaterial
     * @return 结果
     */
    @Override
    public boolean save(BizOrderMaterial bizOrderMaterial) {
        return super.save(bizOrderMaterial);
    }

    /**
     * 删除销售单物料信息
     * @param bizOrderMaterial
     * @return 结果
     */
    @Override
    public boolean remove(BizOrderMaterial bizOrderMaterial) {
        return super.remove(bizOrderMaterial);
    }

    /**
     * 批量删除销售单物料
     * @param ids 需要删除的销售单物料ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteBizOrderMaterialByIds(String[] ids) {
        return mapper.deleteBizOrderMaterialByIds(ids, BaseEntity.DEL_FLAG_DELETE);
    }

    @Override
    public int deleteBizOrderMaterialByOrderId(String orderId) {
        return  mapper.deleteBizOrderMaterialByOrderId(orderId, BaseEntity.DEL_FLAG_DELETE);
    }

    @Transactional
    @Override
    public boolean saveMaterials(BizOrder bizOrder, LoginUser loginUser) {
        BizOrder bizOrder1 = bizOrderService.get(bizOrder.getId());
        List<BizOrderMaterial> bizOrderMaterial = bizOrder.getMaterialList();
        if ("3".equals(bizOrder1.getOrderStatus())){
            bizOrder1.setOrderStatus("4");
            bizOrderService.save(bizOrder1);
        }
        if (bizOrderMaterial !=null && bizOrderMaterial.size()>0){
            for (BizOrderMaterial orderMaterial:bizOrderMaterial){
                if (StringUtils.isNotEmpty(orderMaterial.getGainStatus())){
                    if ("3".equals(orderMaterial.getGainStatus())) {
                        super.remove(orderMaterial);
                    }else {
                        if (StringUtils.isEmpty(orderMaterial.getWarehouseId())){
                            throw new BizException("产品编号:"+orderMaterial.getProductCode()+"的仓库不能为空");
                        }
                        if (StringUtils.isEmpty(orderMaterial.getSpaceId())){
                            throw new BizException("产品编号:"+orderMaterial.getProductCode()+"的仓位不能为空");
                        }
                        updateInventory(orderMaterial,bizOrder1,loginUser);
                    }
                }else {
                 throw new BizException("产品编号:"+orderMaterial.getProductCode()+"的领取类型不能为空");
                }
            }
        }
        return true;
    }

    @Transactional
    public void updateInventory(BizOrderMaterial bizOrderMaterial,BizOrder bizOrder1, LoginUser loginUser){
        BigDecimal gainNumber = bizOrderMaterial.getGainNumber();
        String remark=null;
        if (gainNumber == null){
            throw new BizException("数量不能为空！");
        }
//        if (StringUtils.isEmpty(bizOrderMaterial.getUnit())){
//            throw new BizException("单位不能为空！");
//        }
        if ("2".equals(bizOrderMaterial.getProductType())){
            gainNumber=BigDecimal.ZERO.subtract(gainNumber);
            remark=bizOrderMaterial.getRemark()+","+loginUser.getUsername()+"退料";
        }else if ("1".equals(bizOrderMaterial.getProductType())) {
            remark = "补料";
        }
        if (bizOrderMaterial.getReceivedNumber() != null ){
            bizOrderMaterial.setReceivedNumber(bizOrderMaterial.getReceivedNumber().add(gainNumber));
            bizOrderMaterial.setNumber(bizOrderMaterial.getReceivedNumber().add(gainNumber));
        }else {
            bizOrderMaterial.setReceivedNumber((gainNumber));
            bizOrderMaterial.setNumber((gainNumber));
        }
        String tenantId = SecurityUtils.getTenantId();
        bizOrderMaterial.setTenantId(tenantId);
        super.save(bizOrderMaterial);
        if (StringUtils.isNotEmpty(bizOrderMaterial.getSpaceId())){
//            bizOrderService.changeInventory(bizOrderMaterial);
            BizProductInventory bizProductInventory = bizProductInventoryService.getByProductIdAndSpaceId(bizOrderMaterial.getProductId(),
                    bizOrderMaterial.getSpaceId());
            BizProduct bizProduct = bizProductService.get(bizOrderMaterial.getProductId());
            if (bizProduct.getInventoryFlag() != null && "1".equals(bizProduct.getInventoryFlag())) {
                //计算基础数量
                BigDecimal basicNumber = ConvertRatioNumberUnit.convertRatio(gainNumber, bizOrderMaterial.getUnit(), bizProduct);
                if (bizProductInventory != null) {
                    BigDecimal number = bizProductInventory.getNumber() == null ? BigDecimal.ZERO : bizProductInventory.getNumber();
                    if (number != null && number.compareTo(basicNumber) >= 0) {
                        bizProductInventory.setNumber(number.subtract(basicNumber));
                        bizProductInventory.setAssistNumberA(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioA()).setScale(3, BigDecimal.ROUND_HALF_UP));
                        bizProductInventory.setAssistNumberB(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioB()).setScale(3, BigDecimal.ROUND_HALF_UP));
                        bizProductInventoryService.save(bizProductInventory);
                    } else {
                        throw new BizException("库存不足！");
                    }
                } else {
                    if ("2".equals(bizOrderMaterial.getProductType())) {
                        bizProductInventory = new BizProductInventory();
                        bizProductInventory.setProductId(bizOrderMaterial.getProductId());
                        bizProductInventory.setSpaceId(bizOrderMaterial.getSpaceId());
                        bizProductInventory.setWarehouseId(bizOrderMaterial.getWarehouseId());
                        bizProductInventory.setNumber(BigDecimal.ZERO.subtract(basicNumber));
                        bizProductInventory.setAssistNumberA(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioA()).setScale(3, BigDecimal.ROUND_HALF_UP));
                        bizProductInventory.setAssistNumberB(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioB()).setScale(3, BigDecimal.ROUND_HALF_UP));
                        bizProductInventory.setTenantId(SecurityUtils.getTenantId());
                        bizProductInventoryService.save(bizProductInventory);
                    } else {
                        throw new BizException("未查询到当前库存数据");
                    }
                }
                BizProductInventoryBook productInventoryBook = new BizProductInventoryBook();
                productInventoryBook.setBizDate(DateUtils.getNowDate());
                productInventoryBook.setUnit(bizProduct.getUnit());
                productInventoryBook.setAssistUnitA(bizProduct.getAssistUnitA());
                productInventoryBook.setAssistUnitB(bizProduct.getAssistUnitB());
                productInventoryBook.setInventoryId(bizProductInventory.getId());
                productInventoryBook.setNumber(basicNumber);
                productInventoryBook.setAssistNumberB(basicNumber.multiply(bizProduct.getConvertRatioB()).setScale(3, BigDecimal.ROUND_HALF_UP));
                productInventoryBook.setAssistNumberA(basicNumber.multiply(bizProduct.getConvertRatioA()).setScale(3, BigDecimal.ROUND_HALF_UP));
//            productInventoryBook.setOrderNumber(bizOrderMaterial.getPurchaseCode());
                productInventoryBook.setOrderType(BizConstants.ORDER_TYPE_PURCHASE);
                productInventoryBook.setProductModel(bizProduct.getModel());
                productInventoryBook.setTenantId(SecurityUtils.getTenantId());
                productInventoryBook.setProductId(bizProduct.getId());
                productInventoryBook.setCustomer(bizOrder1.getCustomerId());
                productInventoryBook.setRemark(bizOrderMaterial.getRemark());
                productInventoryBook.setOrderType("1");
                productInventoryBook.setOrderNumber(bizOrder1.getOrderNumber());
                productInventoryBook.setRemark(remark);
                productInventoryBook.setSpaceId(bizOrderMaterial.getSpaceId());
                productInventoryBook.setWarehouseId(bizOrderMaterial.getWarehouseId());
                bizProductInventoryBookService.save(productInventoryBook);
            }
        }else {
            throw new BizException("产品的是否参与库存计算不能为空！");
        }
    }

    @Override
    public List<BizOrderMaterial> getBizOrderMaterialByOrderId(String orderId) {
        List<BizOrderMaterial> list = mapper.getBizOrderMaterialByOrderId(orderId);
        if (list != null && list.size()>0){
            for (BizOrderMaterial bizOrderMaterial : list){
                if (StringUtils.isNotEmpty(bizOrderMaterial.getSpaceId())){
                    BizProductInventory inventory = bizProductInventoryService.getByProductIdAndSpaceId(bizOrderMaterial.getProductId(), bizOrderMaterial.getSpaceId());
                    if (inventory !=null){
                        bizOrderMaterial.setStock(inventory.getNumber());
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<BizOrderMaterialVo> findExportList(BizOrderMaterial bizOrderMaterial) {
        List<BizOrderMaterialVo> list = bizOrderMaterialMapper.findExportList(bizOrderMaterial);
        return list;
    }
    @Override
    public List<BizOrderMaterialVo> findPickList(BizOrderMaterial bizOrderMaterial) {
        List<BizOrderMaterialVo> list = bizOrderMaterialMapper.findPickList(bizOrderMaterial);
        return list;
    }

    /**
     * 分页查询销售单物料列表
     * @param bizOrderMaterial 销售单物料
     * @return 领料明细
     */
    @Override
    public PageInfo<BizOrderMaterialVo> findPageExportList(BizOrderMaterial bizOrderMaterial) {
        PageDomain page = bizOrderMaterial.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        List<BizOrderMaterialVo> bizOrderMaterialVos = bizOrderMaterialMapper.findExportList(bizOrderMaterial);

        return new PageInfo(bizOrderMaterialVos);
    }


    @Override
    public PageInfo<BizOrderMaterialVo> findPagePickList(BizOrderMaterial bizOrderMaterial) {
        PageDomain page = bizOrderMaterial.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        List<BizOrderMaterialVo> bizOrderMaterialVos = bizOrderMaterialMapper.findPickList(bizOrderMaterial);

        return new PageInfo(bizOrderMaterialVos);
    }
}
